package com.ihighest.app.infox.adapter;

import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.ScreenKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.StrKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;

public class NewsAdapter extends BaseAdapter {

	final String TAG = "NewsAdapter";
	private final String READ_NEWS_ID = "readnewsid";
	JSONArray array;
	Context activity;
	LayoutInflater inflater = null;
	// protected ImageLoader imageLoader = ImageLoader.getInstance();
	// DisplayImageOptions options;
	/** 弹出的更多选择框 */
	private PopupWindow popupWindow;
	/** popWindow 关闭按钮 */
	private TextView pop_close, pop_tv_choseItem;
	/* 屏蔽的选择项 type:id */
	List<String> blockList = new LinkedList<>();
	private String Key;

	public NewsAdapter(Context activity, JSONArray array, String key) {
		this.activity = activity;
		this.array = array;
		inflater = LayoutInflater.from(activity);
		this.Key = key;
	}

	public NewsAdapter(Activity activity) {
		this.activity = activity;
		inflater = LayoutInflater.from(activity);

	}

	@Override
	public int getCount() {
		return array == null ? 0 : array.length();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.infox_newslist_item, null);
			holder.tv_id = (TextView) convertView.findViewById(R.id.tv_id);
			holder.comment_count = (TextView) convertView.findViewById(R.id.newsCommentCount);
			holder.item_source = (TextView) convertView.findViewById(R.id.newsProvenance);
			holder.publish_time = (TextView) convertView.findViewById(R.id.newsDate);
			holder.normalItem_image = (ImageView) convertView.findViewById(R.id.newsListItemNameSmallImg);
			holder.item_title = (TextView) convertView.findViewById(R.id.newsListItemName);
			holder.item_bigImage_layout = (RelativeLayout) convertView.findViewById(R.id.newBigImgLayout);
			holder.normalItem_layout = (RelativeLayout) convertView.findViewById(R.id.newSmallImgLayout);
			holder.item_close = (ImageView) convertView.findViewById(R.id.newsClose);
			holder.item_bigImage_title = (TextView) convertView.findViewById(R.id.newsBigItemName);
			holder.item_bigImage = (ImageView) convertView.findViewById(R.id.newsListItemNameBigImg);
			holder.list_item_local = (TextView) convertView.findViewById(R.id.list_item_local);
			holder.noImgLayout = (RelativeLayout) convertView.findViewById(R.id.noImgLayout);
			holder.noImgTitle = (TextView) convertView.findViewById(R.id.noImgItemName);
			holder.frameLayout1 = convertView.findViewById(R.id.frameLayout1);
			holder.parentLayout = (LinearLayout) convertView.findViewById(R.id.item_layout);

		

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.item_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					blockList.clear();
					JSONArray tagsArray = array.getJSONObject(position).getJSONArray("tags");
					JSONArray jsonArray = new JSONArray();
					jsonArray.put(new JSONObject("{tid:'1',ttitle:'重复、旧闻',type:'default'}"));
					jsonArray.put(new JSONObject("{tid:'2',ttitle:'内容质量差',type:'default'}"));
					if (StrKit.isBlank(array.getJSONObject(position).getString("sourceid"))) {
						jsonArray.put(new JSONObject("{tid:'',ttitle:'原创',type:'source'}"));
					} else {
						jsonArray.put(new JSONObject("{tid:'" + array.getJSONObject(position).getString("sourceid") + "',ttitle:'"
								+ array.getJSONObject(position).getString("source") + "',type:'source'}"));
					}
					if (tagsArray != null) {
						for (int i = 0; i < tagsArray.length(); i++) {
							tagsArray.getJSONObject(i).put("type", "tag");
						}
					}
					jsonArray = AppKit.joinJSONArray(jsonArray, tagsArray);
					initPopWindow(new MGridViewAdapter(jsonArray));
					popupWindow.showAtLocation(arg0, Gravity.CENTER, 0, 0);
					popupWindow.setFocusable(true);
					// 设置popwindow如果点击外面区域，便关闭。
					popupWindow.setOutsideTouchable(true);
					popupWindow.update();
					pop_close.setOnClickListener(new OnClickListener() {
						@SuppressLint("NewApi")
						@Override
						public void onClick(View paramView) {
							if (!TextUtils.isEmpty(SharedPreferencesKit.getString(activity, Const.SP_KEY_USER_ID))) {

								StringBuilder sb = new StringBuilder();
								for (String str : blockList) {
									sb.append(str).append(",");
								}
								try {
									Api.post("me/trash", ApiParam.create().addParam("id", array.getJSONObject(position).getString("id"))
											.addParam("type", "1").addParam("ids", sb.toString()), new ApiCallback(activity, true) {
										@Override
										public void handleSuccess(ApiResult result) {

										}

										@Override
										public void handleFailure(Exception e, String msg) {

										}
									}, activity);
								} catch (Exception ex) {
									Log.e(TAG, ex.getMessage(), ex);
								}
								popupWindow.dismiss();
								ToastKit.showShort(activity, "将减少类似内容推荐");
								array.remove(position);
								JSONArray shareArray = SharedPreferencesKit.getJsonArray(activity, Key);
								for (int i = 0; i < shareArray.length(); i++) {
									try {
										if (shareArray.getJSONObject(i).getString("id")
												.equals(array.getJSONObject(position).getString("id"))) {
											// System.out.println("删除");
											shareArray.remove(i);
											SharedPreferencesKit.putJsonArray(activity, Key, shareArray);
										}
									} catch (JSONException e) {
										e.printStackTrace();
									}
								}
								notifyDataSetChanged();
							} else {
								ToastKit.showShort(activity, Const.UN_LOGIN_ALERT);
							}
						}
					});
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}
		});
		try {
			if (TextUtils.isEmpty(array.getJSONObject(position).getString("image"))) {
				// 如果该条目没有图片
				holder.item_bigImage_layout.setVisibility(View.GONE);
				holder.normalItem_layout.setVisibility(View.GONE);
				holder.noImgLayout.setVisibility(View.VISIBLE);
				if (TextUtils.isEmpty(array.getJSONObject(position).getString("title"))) {
					holder.noImgTitle.setText("无标题");
				} else {
					holder.noImgTitle.setText(AppKit.trimString(array.getJSONObject(position).getString("title")));
				}
				String readNewsId = SharedPreferencesKit.getString(activity, READ_NEWS_ID, null);
				if (!TextUtils.isEmpty(readNewsId) && readNewsId.contains(array.getJSONObject(position).getString("id"))) {
					// 如果获取到的id数据不为空，并且包含该条新闻id，将字体设置为灰色
					holder.noImgTitle.setTextColor(Color.GRAY);
				}
			
				
			} else {
				holder.item_bigImage_layout.setVisibility(View.GONE);
				holder.normalItem_layout.setVisibility(View.VISIBLE);
				holder.noImgLayout.setVisibility(View.GONE);
				
				
				
				if (TextUtils.isEmpty(array.getJSONObject(position).getString("title"))) {
					holder.item_title.setText("无标题");
				} else {
					holder.item_title.setText(AppKit.trimString(array.getJSONObject(position).getString("title")));
				}
				// DisplayImageOptions defaultOptions = new
				// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_img_loadrong)
				// .showImageOnFail(R.drawable.infox_img_loadrong).showImageOnLoading(R.drawable.infox_img_loadrong)
				// .cacheInMemory(true).cacheOnDisc(true).build();
				// ImageLoader.getInstance().displayImage(array.getJSONObject(position).getString("image"),
				// holder.normalItem_image,
				// defaultOptions);
				AppKit.SetNormalImg(array.getJSONObject(position).getString("image"), holder.normalItem_image);
				String readNewsId = SharedPreferencesKit.getString(activity, READ_NEWS_ID, null);
				if (!TextUtils.isEmpty(readNewsId) && readNewsId.contains(array.getJSONObject(position).getString("id"))) {
					// 如果获取到的id数据不为空，并且包含该条新闻id，将字体设置为灰色
					holder.item_title.setTextColor(Color.GRAY);
				}
			}
			if (StrKit.isBlank(array.getJSONObject(position).getString("sourceid"))) {
				holder.item_source.setText("原创");
			} else {
				holder.item_source.setText(array.getJSONObject(position).getString("source"));
			}
			holder.tv_id.setText(array.getJSONObject(position).getString("id"));
			holder.comment_count.setText(array.getJSONObject(position).getString("comments") + "条评论");
			holder.publish_time.setText(AppKit.timeToBeforeStr(array.getJSONObject(position).getLong("time")));
			if (TextUtils.isEmpty(array.getJSONObject(position).getString("tag"))) {
				holder.frameLayout1.setVisibility(View.GONE);
				holder.list_item_local.setVisibility(View.GONE);
			} else {
				holder.frameLayout1.setVisibility(View.VISIBLE);
				holder.list_item_local.setVisibility(View.VISIBLE);
				if (array.getJSONObject(position).getString("tag").equals("_HOT")) {
					// 表示该新闻是热门新闻
					holder.list_item_local.setBackgroundResource(R.drawable.infox_information_hotbg);
					holder.list_item_local.setTextColor(activity.getResources().getColor(R.color.hotItemcolor));
					holder.list_item_local.setText("热点");
				} else if (array.getJSONObject(position).getString("tag").equals("_SUB")) {
					// 表示该新闻是订阅新闻
					holder.list_item_local.setBackgroundResource(R.drawable.infox_information_dingyuebg);
					holder.list_item_local.setTextColor(activity.getResources().getColor(R.color.subscriptionItemcolor));
					holder.list_item_local.setText("订阅");
				} else if (array.getJSONObject(position).getString("tag").equals("_PRO")) {
					// 表示该新闻是推广新闻
					holder.list_item_local.setBackgroundResource(R.drawable.infox_information_popularizebg);
					holder.list_item_local.setTextColor(activity.getResources().getColor(R.color.popularizeItemcolor));
					holder.list_item_local.setText("推广");
				} else if (array.getJSONObject(position).getString("tag").equals("_REM")) {
					// 表示该新闻是推荐新闻
					holder.list_item_local.setBackgroundResource(R.drawable.infox_information_recommendbg);
					holder.list_item_local.setTextColor(activity.getResources().getColor(R.color.recommendItemcolor));
					holder.list_item_local.setText("推荐");
				} else {
					holder.list_item_local.setBackgroundResource(R.drawable.infox_information_plantbg);
					holder.list_item_local.setTextColor(activity.getResources().getColor(R.color.orange_yellow));
					holder.list_item_local.setText(array.getJSONObject(position).getString("tag"));// 测试
				}
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		return convertView;
	}

	static class ViewHolder {
		RelativeLayout normalItem_layout;
		// id
		TextView tv_id;
		// title
		TextView item_title;
		// 新闻来源
		TextView item_source;
		// 类似推广之类的标签
		TextView list_item_local;
		// 评论数量
		TextView comment_count;
		// 发布时间
		TextView publish_time;
		// 小图片
		ImageView normalItem_image;
		// 大图片布局
		RelativeLayout item_bigImage_layout;
		// title
		TextView item_bigImage_title;
		ImageView item_bigImage;
		ImageView item_close;
		RelativeLayout noImgLayout;
		TextView noImgTitle;


		View frameLayout1;
		LinearLayout parentLayout;
	}

	// 记录选中的block原因

	/**
	 * 初始化弹出的pop
	 * */
	private void initPopWindow(MGridViewAdapter adapter) {
		View popView = inflater.inflate(R.layout.infox_list_pupopwindow, null);
		popupWindow = new PopupWindow(popView, (int) (ScreenKit.getScreenWidth(activity) * 0.8), LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(new ColorDrawable(0));
		// 设置popwindow出现和消失动画
		// popupWindow.setAnimationStyle(R.style.PopMenuAnimation);
		pop_close = (TextView) popView.findViewById(R.id.onInterest);
		pop_tv_choseItem = (TextView) popView.findViewById(R.id.choseItem);
		GridView reasonView = (GridView) popView.findViewById(R.id.reasonGridview);
		reasonView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	class MGridViewAdapter extends BaseAdapter {
		private final JSONArray mArray;

		MGridViewAdapter(JSONArray arrary) {
			this.mArray = arrary;
		}

		@Override
		public int getCount() {
			return mArray != null ? mArray.length() : 0;
		}

		@Override
		public Object getItem(int position) {
			return position;

		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			BlockViewHolder holder = null;
			if (view == null) {
				view = View.inflate(activity, R.layout.infox_information_popup_item, null);
				holder = new BlockViewHolder();
				holder.box = (CheckBox) view.findViewById(R.id.reasonItem);
				view.setTag(holder);
			} else {
				holder = (BlockViewHolder) view.getTag();
			}

			holder.box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if (blockList.contains(buttonView.getTag(R.id.tag_1) + ":" + buttonView.getTag(R.id.tag_2))) {
						blockList.remove(buttonView.getTag(R.id.tag_1) + ":" + buttonView.getTag(R.id.tag_2));
					} else {
						blockList.add(buttonView.getTag(R.id.tag_1) + ":" + buttonView.getTag(R.id.tag_2));
					}
					if (blockList.size() > 0) {
						pop_close.setText("精准屏蔽");
						pop_tv_choseItem.setText("已选" + blockList.size() + "个理由");
					} else {
						pop_close.setText("不感兴趣");
						pop_tv_choseItem.setText("可选理由，精准屏蔽");
					}
				}
			});

			try {
				JSONObject json = mArray.getJSONObject(position);
				holder.box.setText(json.getString("ttitle"));
				holder.box.setTag(R.id.tag_1, json.getString("tid"));
				holder.box.setTag(R.id.tag_2, json.getString("type"));
				if (StrKit.isBlank(json.getString("tid"))) {
					holder.box.setEnabled(false);
				}
			} catch (JSONException e) {
				Log.e(TAG, e.getMessage(), e);
			}

			return view;
		}
	}

	static class BlockViewHolder {
		CheckBox box;
	}

	/**
	 * 替换当前数据源数据
	 * 
	 * @param moreArry
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:23
	 */
	public void setData(JSONArray jsonArray) {
		array = jsonArray;
		notifyDataSetChanged();
	}

	/**
	 * 向已有数据源中追加数据
	 * 
	 * @param jsonArray
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:00
	 */
	public void appendData(JSONArray jsonArray) {
		try {
			array = AppKit.joinJSONArray(array, jsonArray);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		notifyDataSetChanged();
	}
}
